package com.meihua.shellapp.view;

import android.content.Context;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.meihua.shellapp.R;


/**
 * 展开收起的text
 */

public class ExpandableTextView extends RelativeLayout {
    int maxExpandLines = 1;
    TextView id_source_textview;
    TextView id_expand_textview;
    private boolean isCollapsed = true;

    public ExpandableTextView(Context context) {
        this(context, null);
    }

    public ExpandableTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        LayoutInflater.from(context).inflate(R.layout.textview_expandable, this, true);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        id_source_textview = (TextView) findViewById(R.id.id_source_textview);
        id_expand_textview = (TextView) findViewById(R.id.id_expand_textview);
        id_expand_textview.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                isCollapsed = !isCollapsed;
                if (isCollapsed) {
                    id_expand_textview.setText("全文");
                    id_source_textview.setMaxLines(1);
                    id_source_textview.setEllipsize(TextUtils.TruncateAt.END);
                } else {
                    id_expand_textview.setText("收起");
                    id_source_textview.setMaxLines(Integer.MAX_VALUE);
                    id_source_textview.setEllipsize(null);
                }
                requestLayout();
            }
        });

    }


    public void setText(String text) {
        id_source_textview.setMaxLines(Integer.MAX_VALUE);
        id_source_textview.setText(text);
        final boolean[] ismax = {true};
        id_source_textview.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (ismax[0]) {
                    ismax[0] = false;
                } else {
                    return;
                }
                if (id_source_textview.getLineCount() <= maxExpandLines) {
                    id_expand_textview.setVisibility(GONE);
                } else {
                    id_expand_textview.setVisibility(VISIBLE);
                }
                id_source_textview.setMaxLines(maxExpandLines);
            }
        });
    }


}
